package com.reekr.a5t.web.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.method.*;
import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import com.reekr.a5t.model.User;
import com.reekr.a5t.web.annotation.SessionInfo;
import com.reekr.a5t.web.controller.IndexController;

public class SessionInfoInterceptor extends HandlerInterceptorAdapter {


	@Override
	public boolean preHandle(HttpServletRequest request,
			HttpServletResponse response, Object handler) throws Exception {
		HandlerMethod handlerMethod = (HandlerMethod) handler;
		
		SessionInfo sessionInfo = handlerMethod.getBeanType().getAnnotation(SessionInfo.class);
		if(null == sessionInfo) sessionInfo = handlerMethod.getMethodAnnotation(SessionInfo.class);
		if(null == sessionInfo) {
			return true;
		}
		
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(IndexController.KEY_USER);
		if(null == user){
			response.sendRedirect(request.getContextPath());
			return false;
		}
		return true;
	}
	
	
}
